/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * PmProjectController
 * 项目基本信息
 * <p>
 * 修改纪录
 * 2020-05-18 版本：1.0 liwanpeng 创建。
 *
 * @version 版本：1.0
 * @author 作者：liwanpeng
 * 创建日期：2020-05-18
 */

package com.topscomm.pm.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboItemDetailsEntity;
import com.topscomm.cbo.pojo.CboSysParamEntity;
import com.topscomm.cbo.service.impl.CboItemDetailsService;
import com.topscomm.cbo.service.impl.CboSysParamService;
import com.topscomm.pm.controller.auto.PmProjectControllerAuto;
import com.topscomm.pm.pojo.*;
import com.topscomm.pm.service.impl.*;
import com.topscomm.pm.utils.MisStringUtil;
import com.topscomm.pub.util.*;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.Query;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.ITapService;
import com.topscomm.tap.common.ParameterCache;
import com.topscomm.tap.common.SessionUserBean;
import com.topscomm.tap.common.TapSystemConst.TapOperationTypeEnum;
import com.topscomm.tap.security.SecurityUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author: liwanpeng
 * @date: 2020-05-18
 * @description:项目基本信息Controller
 * @modify:
 */
@RestController
@RequestMapping("pm/project")
public class PmProjectController extends PmProjectControllerAuto implements IPmProjectController {
	@Resource
	private PmMilepostService pmMilepostService;
	@Resource
	private PmRiskIdentifyService pmRiskIdentifyService;
	@Resource
	private PmProblemsService pmProblemsService;
	@Resource
	private PmTaskService pmTaskService;
	@Resource
	private PmContractService pmContractService;
	@Resource
	private PmInvoiceApplyService pmInvoiceApplyService;
	@Resource
	private PmRecBillService pmRecBillService;
	@Resource
	private PmTeamService pmTeamService;
	@Resource
	private PmTaskLogService pmTaskLogService;
	@Resource
	private CboItemDetailsService cboItemDetailsService;
	@Autowired
	@Qualifier("securityUserDetailsService")
	private UserDetailsService userDetailsService;
	@Resource(name ="pmProjectService")
	private PmProjectService pmProjectService;
	/**
	 * @param paraMap
	 * @return
	 * @author: liwanpeng
	 * @date: 2020-05-18
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_projectmanagername")) {
			String value = paraMap.get("qry_projectmanagername").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectmanagername like '%{0}%'", value);
		}

		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		// 查询可以执行其他变更的项目
		if (paraMap.containsKey("qry_stateflag")) {
			String value = paraMap.get("qry_stateflag").toString();
			if ("1".equals(value))
				sql.appendSingle(" and state not in (0,2) ");
		}
		// 项目状态
		if (paraMap.containsKey("qty_projectstate")) {
			String value = paraMap.get("qty_projectstate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = '{0}'", value);
		}
		// 项目名称
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (name like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (code like '%{0}%')", value);
		}
		// 是否外包
		if (paraMap.containsKey("qry_ispurchase")) {
			String value = paraMap.get("qry_ispurchase").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and ispurchase = '{0}'", value);
		}
		// 开工日期（开始时间）
		if (paraMap.containsKey("qry_actualstarttimestart")) {
			String value = paraMap.get("qry_actualstarttimestart").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and actualstarttime >= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", value);
		}
		// 开工日期（结束时间）
		if (paraMap.containsKey("qry_actualstarttimeend")) {
			String value = paraMap.get("qry_actualstarttimeend").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and actualstarttime <= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", value);
		}
		// 完工日期（开始时间）
		if (paraMap.containsKey("qry_actualendtimestart")) {
			String value = paraMap.get("qry_actualendtimestart").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and actualendtime >= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", value);
		}
		// 完工日期（结束时间）
		if (paraMap.containsKey("qry_actualendtimeend")) {
			String value = paraMap.get("qry_actualendtimeend").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and actualendtime <= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", value);
		}
		// 查询正在运行中的项目
		if (paraMap.containsKey("qry_processflag")) {
			String value = paraMap.get("qry_processflag").toString();
			if ("1".equals(value))
				sql.appendSingle(" and projectstate in ('1','2','3','4')");
		}
		// 查询可以申请变更的项目
		if (paraMap.containsKey("qry_changeFlag")) {
			String value = paraMap.get("qry_changeFlag").toString();
			if ("1".equals(value))
				sql.appendSingle(" and projectstate in ('1','2','3','4','5')");
		}
		// 查询已暂停的项目
		if (paraMap.containsKey("qry_stopflag")) {
			String value = paraMap.get("qry_stopflag").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = {0}", value);
		}
		// 查询可以延期的项目
		if (paraMap.containsKey("qry_tobedelayflag")) {
			String value = paraMap.get("qry_tobedelayflag").toString();
			if ("24".equals(value))
				sql.appendSingle(" and projectstate in ('2','4')");
		}
		// 查询待开工的项目
		if (paraMap.containsKey("qry_tobestartflag")) {
			String value = paraMap.get("qry_tobestartflag").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = {0}", value);
		}
		// 查询可以闭环的项目
		if (paraMap.containsKey("qry_fromClose")) {
			String value = paraMap.get("qry_fromClose").toString();
			if ("1".equals(value)) {
				sql.appendSingle(" and projectstate = '3'");
				// 去掉四个金额必须一致的限定条件
//				sql.appendSingle(" and projectmoney = recbillmoney");
//				sql.appendSingle(" and projectmoney = billmoney");
//				sql.appendSingle(" and projectmoney = contractmoney");
			}
		}
		// 查询项目经理
		if (paraMap.containsKey("qry_projectmanagername")) {
			String value = paraMap.get("qry_projectmanagername").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectmanagername like '%{0}%'", value);
		}
		// 项目报表查询条件
		if (paraMap.containsKey("qry_nameStatistics")) {
			String value = paraMap.get("qry_nameStatistics").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (name like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_codeStatistics")) {
			String value = paraMap.get("qry_codeStatistics").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (code like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_dateStatisticsStart")) {
			String value = paraMap.get("qry_dateStatisticsStart").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and createon >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_dateStatisticsEnd")) {
			String value = paraMap.get("qry_dateStatisticsEnd").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and createon <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_projectstateStatistics")) {
			String value = paraMap.get("qry_projectstateStatistics").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = '{0}'", value);
		}
		// 查询销售经理
		if (paraMap.containsKey("qry_areamanagername")) {
			String value = paraMap.get("qry_areamanagername").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and areamanagername like '%{0}%'", value);
		}

		if (paraMap.containsKey("qry_projectstate")) {
			String value = paraMap.get("qry_projectstate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = {0}", value);
		}

		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String[] params = {"misdeptheader.deptcode","'%'"};
			sql.appendSingle(" and ( exists (select project.id from pmproject project left join misdeptheader on project.ownerdeptcode like "
							+ SQLAdapter.concat(params) +
							" where ( project.id = PMPROJECT.id and ( project.projectmanagercode = '{0}' or  misdeptheader.usercode='{0}' OR project.AREAMANAGERCODE = '{0}' ))) or usercode = '{0}'",
					this.getUserBean().getUser().getCode());
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select,"", "PmProject", this.getUserBean());
			if (StringUtil.isEmpty(dataPession)) {
			 	sql.appendSingle(" ) ");
			} else {
				sql.appendSingle(" or {0}) ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @param paraMap
	 * @return
	 * @author: duzehou
	 * @date: 2020-05-18
	 * @description:Fds取数
	 * @modify:
	 */
	protected String spellListSqlFds(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		// 项目名称
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (name like '%{0}%')", value);
		}
		// 项目编号
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (code like '%{0}%')", value);
		}
		SessionUserBean userBean = pmProjectService.querySessionUserBean(ConvertUtil.convertToString(paraMap.get("qry_usercode")));

		//不查询已关闭的机会点/线索
		sql.appendSingle(" and {0} not in ({1})",PmProjectEntity.FieldProjectstate, "'21','22'" ); //21,22为项目已报废、强制关闭

		if (userBean.getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String[] params = {"misdeptheader.deptcode","'%'"};
			sql.appendSingle(" and ( exists (select project.id from pmproject project left join misdeptheader on project.ownerdeptcode like "
							+ SQLAdapter.concat(params) +
							" where ( project.id = PMPROJECT.id and ( project.projectmanagercode = '{0}' or  misdeptheader.usercode='{0}' OR project.AREAMANAGERCODE = '{0}' ))) or usercode = '{0}'"
							+ " or exists (select 1 from pmteam pt where pt.projectid = pmProject.id and pt.usercode = '{0}' and pt.enabled = 1)",
					userBean.getUser().getCode());
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select,"", "PmProject", userBean);
			if (StringUtil.isEmpty(dataPession)) {
				sql.appendSingle(" ) ");
			} else {
				sql.appendSingle(" or {0}) ", dataPession);
			}
		}
		return sql.toString();
	}
	/**
	 * @param paraMap
	 * @return
	 * @author: duzehou
	 * @date: 2020-05-18
	 * @description:Fds取数
	 * @modify:
	 */
	protected String spellListSqlFdsFund(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		// 项目名称
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (name like '%{0}%')", value);
		}
		// 项目编号
		if (paraMap.containsKey("qry_code_in")) {
			String value = paraMap.get("qry_code_in").toString();
			if (!StringUtil.isEmpty(value)) {
				value = "'" + value.replaceAll(",", "','") + "'";
				sql.appendSingle(" and code in ({0}) ", value);
			}
		}
		return sql.toString();
	}
	/**
	 * @description: FDS取数 线索查询列表
	 * @param paraMap
	 * @return
	 * @author: duzehou
	 * @date:
	 * @modify:
	 */
	@GetMapping(value = "/fmsList")
	public ResponseResult<Object> fmsList(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			// 校验FMS系统传递key值
			String fmsToken = ParameterCache.getValue("FmsTokenProject");
			if (!fmsToken.equals(ConvertUtil.convertToString(paraMap.get("appKey")))) {
				throw new ServiceException("接口校验失败，请联系管理员！");
			}
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSqlFds(paraMap);
			int totalCount = this.service.getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPageFds(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
			}else{
				tempList = this.service.queryMapByWhereFdsFund(sqlWhere);
			}
			// this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/**
	 * @description: FDS取数 线索金额查询列表
	 * @param paraMap
	 * @return
	 * @author: duzehou
	 * @date:
	 * @modify:
	 */
	@GetMapping(value = "/fmsFundList")
	public ResponseResult<Object> fmsFundList(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			// 校验FMS系统传递key值
			String fmsToken = ParameterCache.getValue("FmsTokenProject");
			if (!fmsToken.equals(ConvertUtil.convertToString(paraMap.get("appKey")))) {
				throw new ServiceException("接口校验失败，请联系管理员！");
			}
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSqlFdsFund(paraMap);
			int totalCount = this.service.getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = this.service.queryMapForPageFds(sqlWhere, query.getCurrentPage(), query.getPageSize(),
						query.getSidx(), query.getSord());
			}else{
				tempList = this.service.queryMapByWhereFdsFund(sqlWhere);
			}
//			 this.service.setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
	//=========================项目报表相关====================================================================================================

	protected String spellListSqlStatistics(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 ");
		// 项目报表查询条件
		if (paraMap.containsKey("qry_nameStatistics")) {
			String value = paraMap.get("qry_nameStatistics").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (name like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_codeStatistics")) {
			String value = paraMap.get("qry_codeStatistics").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (code like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_projectmanagername")) {
			String value = paraMap.get("qry_projectmanagername").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectmanagername like '%{0}%'", value);
		}
		// 项目名称
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (name like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (code like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_dateStatisticsStart")) {
			String value = paraMap.get("qry_dateStatisticsStart").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and createon >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_dateStatisticsEnd")) {
			String value = paraMap.get("qry_dateStatisticsEnd").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and createon <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
//		if (paraMap.containsKey("qry_projectstateStatistics")) {
//			String value = paraMap.get("qry_projectstateStatistics").toString();
//            if(!StringUtil.isEmpty(value)){
//                sql.appendSingle("and projectstate = '{0}'",value);
//			}
//		}


		if (paraMap.containsKey("qry_projectstateStatistics")) {
			String value = paraMap.get("qry_projectstateStatistics").toString();
			if(!StringUtil.isEmpty(value)){
				sql.appendSingle("and projectstate in ({0})",value);
			}
		}

		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
        {
            String dataPession = service.getDataPermission(TapOperationTypeEnum.Select,"", "PmProject",
                    this.getUserBean());
            if (StringUtil.isEmpty(dataPession)) {
                String[] params = {"misdeptheader.deptcode","'%'"};
                sql.appendSingle(" and ( exists (select project.id from pmproject project left join misdeptheader on project.ownerdeptcode like "
                                + SQLAdapter.concat(params) +
                                " where ( project.id = PMPROJECT.id and ( project.projectmanagercode = '{0}' or  misdeptheader.usercode='{0}' OR project.AREAMANAGERCODE = '{0}' or project.usercode = '{0}'  )))) ",
                        this.getUserBean().getUser().getCode());
            }  else// 使用数据权限
            {
                sql.appendSingle(" and {0} ", dataPession);
            }
        }
		return sql.toString();
	}

	@GetMapping("/listStatistics33")
	public ResponseResult<Object> list(@RequestBody(required = false) List<Map<String,Object>> datalist){
		try {
			Map<String, Object> hashmap = new HashMap<>();
			System.out.println(datalist);
			for (Map<String,Object> d:datalist
			) {
				 hashmap = BaseUtil.decodeSecureMap(d);
			}

			Query query = new Query(hashmap);
			String sqlWhere = this.spellListSqlStatistics(hashmap);
			int totalCount = ((ITapService)this.service).getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = ((ITapService)this.service).queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
			} else {
				tempList = ((ITapService)this.service).queryMapByWhere(sqlWhere);
			}

			((ITapService)this.service).setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}



	@GetMapping({"/listStatistics"})
	public ResponseResult<Object> listStatistics(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSqlStatistics(paraMap);
			int totalCount = ((ITapService)this.service).getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = ((ITapService)this.service).queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
			} else {
				tempList = ((ITapService)this.service).queryMapByWhere(sqlWhere);
			}
			((ITapService)this.service).setDispFields(tempList);
			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}



    protected String spellListSqlStatisticsRef(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" enabled=1 ");
        // 项目报表查询条件
        if (paraMap.containsKey("qry_nameStatistics")) {
            String value = paraMap.get("qry_nameStatistics").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (name like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_codeStatistics")) {
            String value = paraMap.get("qry_codeStatistics").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (code like '%{0}%')", value);
        }
        // 项目名称
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (name like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_code")) {
            String value = paraMap.get("qry_code").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and (code like '%{0}%')", value);
        }
        if (paraMap.containsKey("qry_dateStatisticsStart")) {
            String value = paraMap.get("qry_dateStatisticsStart").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and createon >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_dateStatisticsEnd")) {
            String value = paraMap.get("qry_dateStatisticsEnd").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and createon <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        if (paraMap.containsKey("qry_projectstateStatistics")) {
            String value = paraMap.get("qry_projectstateStatistics").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and projectstate = '{0}'", value);
        }
        return sql.toString();
    }



	protected String spellListSqlRef(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" enabled=1 and state=9 ");

		// 项目参照查询时，只能查询出项目立项中已审批完的单据
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and code like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state={0}", value);
		}
		if (paraMap.containsKey("qry_docno")) {
			String value = paraMap.get("qry_docno").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docno like '%{0}%'", value);
		}
		if (paraMap.containsKey("qry_projectmanagername")) {
			String value = paraMap.get("qry_projectmanagername").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectmanagername like '%{0}%'", value);
		}

		if (paraMap.containsKey("qry_begindocdate")) {
			String value = paraMap.get("qry_begindocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_enddocdate")) {
			String value = paraMap.get("qry_enddocdate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and docdate <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_deptname")) {
			String value = paraMap.get("qry_deptname").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (deptid in ( SELECT id from CboDept where fullname like '%{0}%'))", value);
		}
		if (paraMap.containsKey("qry_username")) {
			String value = paraMap.get("qry_username").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (username like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_deptcode")) {
			String value = paraMap.get("qry_deptcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and deptcode like '{0}%'", value);
		}
		// 查询可以执行其他变更的项目
		if (paraMap.containsKey("qry_stateflag")) {
			String value = paraMap.get("qry_stateflag").toString();
			if ("1".equals(value))
				sql.appendSingle(" and state not in (0,2) ");
		}
		// 项目状态
		if (paraMap.containsKey("qty_projectstate")) {
			String value = paraMap.get("qty_projectstate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = '{0}'", value);
		}


		// 是否外包
		if (paraMap.containsKey("qry_ispurchase")) {
			String value = paraMap.get("qry_ispurchase").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and ispurchase = '{0}'", value);
		}
		// 开工日期（开始时间）
		if (paraMap.containsKey("qry_actualstarttimestart")) {
			String value = paraMap.get("qry_actualstarttimestart").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and actualstarttime >= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", value);
		}
		// 开工日期（结束时间）
		if (paraMap.containsKey("qry_actualstarttimeend")) {
			String value = paraMap.get("qry_actualstarttimeend").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and actualstarttime <= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", value);
		}
		// 完工日期（开始时间）
		if (paraMap.containsKey("qry_actualendtimestart")) {
			String value = paraMap.get("qry_actualendtimestart").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and actualendtime >= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", value);
		}
		// 完工日期（结束时间）
		if (paraMap.containsKey("qry_actualendtimeend")) {
			String value = paraMap.get("qry_actualendtimeend").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and actualendtime <= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", value);
		}
		// 查询正在运行中的项目
		if (paraMap.containsKey("qry_processflag")) {
			String value = paraMap.get("qry_processflag").toString();
			if ("1".equals(value))
				sql.appendSingle(" and projectstate in ('1','2','3','4')");
		}
		// 查询可以申请变更的项目
		if (paraMap.containsKey("qry_changeFlag")) {
			String value = paraMap.get("qry_changeFlag").toString();
			if ("1".equals(value))
				sql.appendSingle(" and projectstate in ('1','2','3','4','5')");
		}
		// 查询已暂停的项目
		if (paraMap.containsKey("qry_stopflag")) {
			String value = paraMap.get("qry_stopflag").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = {0}", value);
		}
		// 查询可以延期的项目
		if (paraMap.containsKey("qry_tobedelayflag")) {
			String value = paraMap.get("qry_tobedelayflag").toString();
			if ("24".equals(value))
				sql.appendSingle(" and projectstate in ('2','4')");
		}
		// 查询待开工的项目
		if (paraMap.containsKey("qry_tobestartflag")) {
			String value = paraMap.get("qry_tobestartflag").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = {0}", value);
		}
		// 查询可以闭环的项目
		if (paraMap.containsKey("qry_fromClose")) {
			String value = paraMap.get("qry_fromClose").toString();
			if ("1".equals(value)) {
				sql.appendSingle(" and projectstate = '3'");
				// 去掉四个金额必须一致的限定
//				sql.appendSingle(" and projectmoney = recbillmoney");
//				sql.appendSingle(" and projectmoney = billmoney");
//				sql.appendSingle(" and projectmoney = contractmoney");
			}
		}
		// 查询项目经理
		if (paraMap.containsKey("qry_projectmanagername")) {
			String value = paraMap.get("qry_projectmanagername").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectmanagername like '%{0}%'", value);
		}
		// 项目报表查询条件
		if (paraMap.containsKey("qry_nameStatistics")) {
			String value = paraMap.get("qry_nameStatistics").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (name like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_codeStatistics")) {
			String value = paraMap.get("qry_codeStatistics").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and (code like '%{0}%')", value);
		}
		if (paraMap.containsKey("qry_dateStatisticsStart")) {
			String value = paraMap.get("qry_dateStatisticsStart").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and createon >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
		}
		if (paraMap.containsKey("qry_dateStatisticsEnd")) {
			String value = paraMap.get("qry_dateStatisticsEnd").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and createon <= {0}", SQLAdapter.toDateLong(value + " 23:59:59"));
		}
		if (paraMap.containsKey("qry_projectstateStatistics")) {
			String value = paraMap.get("qry_projectstateStatistics").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = '{0}'", value);
		}
		// 查询销售经理
		if (paraMap.containsKey("qry_areamanagername")) {
			String value = paraMap.get("qry_areamanagername").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and areamanagername like '%{0}%'", value);
		}

		if (paraMap.containsKey("qry_projectstate")) {
			String value = paraMap.get("qry_projectstate").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectstate = {0}", value);
		}

		if (paraMap.containsKey("qry_where")) {
			String value = paraMap.get("qry_where").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and {0}", value);
		}
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select,"", "PmProject",
					this.getUserBean());
			if (StringUtil.isEmpty(dataPession)) {
				String[] params = {"misdeptheader.deptcode","'%'"};
				sql.appendSingle(" and ( exists (select project.id from pmproject project left join misdeptheader on project.ownerdeptcode like "
								+ SQLAdapter.concat(params) +
								" where ( project.id = PMPROJECT.id and ( project.projectmanagercode = '{0}' or  misdeptheader.usercode='{0}' OR project.AREAMANAGERCODE = '{0}' ))) or usercode = '{0}')",
						this.getUserBean().getUser().getCode());
			}  else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}


    @GetMapping({"/refListStatistics"})
    public ResponseResult<Object> refListStatistics(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            paraMap = BaseUtil.decodeSecureMap(paraMap);
            Query query = new Query(paraMap);
            String sqlWhere = this.spellListSqlStatisticsRef(paraMap);
            int totalCount = ((ITapService)this.service).getCount(sqlWhere);
            List<Map<String, Object>> tempList = null;
            if (query.getPageSize() > 0) {
                tempList = ((ITapService)this.service).queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
            } else {
                tempList = ((ITapService)this.service).queryMapByWhere(sqlWhere);
            }

            ((ITapService)this.service).setDispFields(tempList);
            Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }
	//=========================项目报表相关结束====================================================================================================

	/**
	 * 获取综合项目信息
	 *
	 * @return
	 */
	@GetMapping("/overallProjectInfo")
	public ResponseResult<Object> overallProjectInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
//		List<PmProjectEntity> projectList = sysIndexProject(paraMap);
		List<PmProjectEntity> projectList = sysIndexProjectpprovaltimeIsNotNull(paraMap);

		if (projectList != null && projectList.size() > 0) {
			// 获取项目类别
			List<Map<String, Object>> categoryList = datacodeCache.getCodeListMap("PmProjectCategory", "", "sortcode");
			// 获取项目状态
			List<Map<String, Object>> projectStateList = datacodeCache.getCodeListMap("PmProjectState", "", "sortcode");
			List<Map<String, Object>> projectStateListForMobile = projectStateList.stream()
					.filter(state -> (!"0".equals(ConvertUtil.convertToString(state.get("code")))
							&& !"21".equals(ConvertUtil.convertToString(state.get("code")))
							&& !"22".equals(ConvertUtil.convertToString(state.get("code")))
							&& !"20".equals(ConvertUtil.convertToString(state.get("code")))))
					.collect(Collectors.toList());
			List<Map<String, Object>> categoryEchartsData = new ArrayList<>();
			// 按类别统计
			for (Map<String, Object> category : categoryList) {
				String categoryCode = ConvertUtil.convertToString(category.get("code"));
				int categoryNum = 0;
				Map<String, Object> resultTemp = new HashMap<>();
				for (PmProjectEntity projectEntity : projectList) {
					if (projectEntity.getCategory().equals(categoryCode)) {
						categoryNum++;
					}
				}
				resultTemp.put("name", category.get("name"));
				resultTemp.put("code", category.get("code"));
				resultTemp.put("value", categoryNum);
				categoryEchartsData.add(resultTemp);
			}
			// 按照 value 排序
			categoryEchartsData = categoryEchartsData.stream()
					.sorted(Comparator.comparing(this::sortedForProjectType).reversed()).collect(Collectors.toList());
			List<Map<String, Object>> otherCategoryEchartsData = new ArrayList<>();
			List<Map<String, Object>> top6CategoryEchartsData = new ArrayList<>();

			if (categoryEchartsData.size() >= 6) {

				top6CategoryEchartsData = categoryEchartsData.subList(0, 7);
				otherCategoryEchartsData = categoryEchartsData.subList(7, categoryEchartsData.size() - 1);
				int otherCategoryNum = 0;
				for (Map<String, Object> item : otherCategoryEchartsData) {
					otherCategoryNum = otherCategoryNum + ConvertUtil.convertToInt(item.get("value"));
				}
				Map<String, Object> resultTemp = new HashMap<>();
				resultTemp.put("name", "其他");
				resultTemp.put("code", "other");
				resultTemp.put("value", otherCategoryNum);
				top6CategoryEchartsData.add(resultTemp);
			} else {
				top6CategoryEchartsData = categoryEchartsData;
				Map<String, Object> resultTemp = new HashMap<>();
				resultTemp.put("name", "其他");
				resultTemp.put("code", "other");
				resultTemp.put("value", 0);
				top6CategoryEchartsData.add(resultTemp);
			}
			// 按状态统计
			List<Map<String, Object>> echartsDataForProjectState = new ArrayList<>();
			for (Map<String, Object> stat : projectStateList) {
//				String categoryCode = ConvertUtil.convertToString(stat.get("code"));
				long categoryCode = Long.parseLong(stat.get("code").toString());
				int categoryNum = 0;
				Map<String, Object> resultTemp = new HashMap<>();
				for (PmProjectEntity projectEntity : projectList) {
					if (projectEntity.getProjectstate()!=0&&projectEntity.getProjectstate()==categoryCode) {
						categoryNum++;
					}
				}
				resultTemp.put("name", stat.get("name"));
				resultTemp.put("code", stat.get("code"));
				resultTemp.put("value", categoryNum);
				echartsDataForProjectState.add(resultTemp);
			}
			// 按状态统计
			List<Map<String, Object>> echartsDataForProjectStateForMobile = new ArrayList<>();
			int totalcount=0;
			for (Map<String, Object> stat : projectStateListForMobile) {
//				String categoryCode = ConvertUtil.convertToString(stat.get("code"));
				long categoryCode = Long.parseLong(stat.get("code").toString());
				int categoryNum = 0;
				Map<String, Object> resultTemp = new HashMap<>();
				for (PmProjectEntity projectEntity : projectList) {
					if (projectEntity.getProjectstate()!=0&&projectEntity.getProjectstate()==categoryCode) {
						categoryNum++;
					}
				}
				totalcount+=categoryNum;
				resultTemp.put("name", stat.get("name"));
				resultTemp.put("code", stat.get("code"));
				resultTemp.put("value", categoryNum);
				echartsDataForProjectStateForMobile.add(resultTemp);
			}
			// 手机端要求返回全部数量的一个值
			HashMap<String, Object> totalmap = new HashMap<String, Object>();
			totalmap.put("name","全部");
			totalmap.put("code","TotalProject");
			totalmap.put("value",totalcount);
			echartsDataForProjectStateForMobile.add(totalmap);

			Map<String, Object> result = new HashMap<>();
			// result.put("projectList", projectList);
			result.put("catagoryData", top6CategoryEchartsData);
			result.put("projectStatData", echartsDataForProjectState);
			result.put("projectStatDataForMobile", echartsDataForProjectStateForMobile);
			return ResponseResult.ok(result);
		} else {
			return ResponseResult.error("您没有任何项目。");

		}

	}

	/**
	 * 手机端项目信息
	 *
	 * @return
	 */
	@GetMapping("/loadProjectInfoForMobile")
	public ResponseResult<Object> loadProjectInfoForMobile(
			@RequestParam(required = false) Map<String, Object> paraMap) {
		String projectId = ConvertUtil.convertToString(paraMap.get("id"));
		if (projectId == null || "".equals(projectId)) {
			return ResponseResult.error("项目Id不得为空");
		}
		// 生成手机端需要的数据格式
		Map<String, Object> mainListData = this.service.queryMapById(paraMap.get("id").toString());
		// 将取出的详细数据放入
		List<Map<String, Object>> mainList = new ArrayList<>();
		mainList.add(mainListData);
		Map<String, Object> resultDataMap = new HashMap<>();
		resultDataMap.put("mainList", mainList);
		// resultDataMap.put("mainList", mainList);
		// 获取页面（约定：app管理页面配置中的页面编码对应controller表名）
		appPageService.getPageInfo("PmProject", resultDataMap);
		return ResponseResult.ok(resultDataMap);
	}

	/**
	 * 手机端项目列表
	 *
	 * @return
	 */
	@GetMapping("/projectListForMobile")
	public ResponseResult<Object> projectListForMobile(@RequestParam(required = false) Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		String sqlWhere = this.spellListSql(paraMap);
		sqlWhere = sqlWhere+" and projectstate in (1,2,3,4,5) and approvaltime is not null";
		int totalCount = this.service.getCount(sqlWhere);
		List<Map<String, Object>> tempList = null;
		if (query.getPageSize() > 0) {
			tempList = this.service.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(),
					query.getSidx(), query.getSord());
		} else
			tempList = this.service.queryMapByWhere(sqlWhere);
		this.service.setDispFields(tempList);
		Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
		return ResponseResult.ok(page);
	}
	/**
	 * 手机端项目列表(查询)
	 *
	 * @return
	 */
	@GetMapping("/projectListForMobileForSearch")
	public ResponseResult<Object> projectListForMobileForSearch(@RequestParam(required = false) Map<String, Object> paraMap) {
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		String sqlWhere = this.spellListSql(paraMap);
		sqlWhere = sqlWhere+" and projectstate in (1,2,3,4,5,20) and approvaltime is not null";
		int totalCount = this.service.getCount(sqlWhere);
		List<Map<String, Object>> tempList = null;
		if (query.getPageSize() > 0) {
			tempList = this.service.queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(),
					query.getSidx(), query.getSord());
		} else
			tempList = this.service.queryMapByWhere(sqlWhere);
		this.service.setDispFields(tempList);
		Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
		return ResponseResult.ok(page);
	}
	/**
	 * 项目信息概况
	 *
	 * @return
	 */
	@PostMapping("/projectInfoSurvey")
	public ResponseResult<Object> projectInfoSurvey(@RequestBody Map<String, Object> paraMap) {
		List<Map<String, Object>> resultMapList = new ArrayList<>();
		List<PmProjectEntity> projectList = sysIndexProject(paraMap);
		// ================================筛选超期未结束项目(计划完工时间早于当前时间，且项目状态不为20：已闭环（饼图展示）
		// 21：已报废 22：强制关闭)================================
		Map<String, Object> overdueResultMap = new HashMap<>();
		// List<PmProjectEntity> overdueProjects = projectList.stream()
		// .filter(project -> !("20".equals(project.getProjectstate()) ||
		// "21".equals(project.getProjectstate())
		// || "22".equals(project.getProjectstate()))
		// && (project.getPlanendtime().getTime() < (new Date()).getTime()))
		// .collect(Collectors.toList());
		List<PmProjectEntity> overdueProjects = projectList.stream()
				.filter(project -> ("4".equals(project.getProjectstate()))
						&& (project.getPlanendtime().getTime() < (new Date()).getTime()))
				.collect(Collectors.toList());
		overdueResultMap.put("code", "overdueProjectNum");
		overdueResultMap.put("name", "超期项目");
		overdueResultMap.put("iconImg", "/static/images/paojectManager/overdueTime.png");
		overdueResultMap.put("value", overdueProjects.size());
		resultMapList.add(overdueResultMap);
		// =========================查询超期未结束里程碑(状态为未达成，且计划结束时间在今日之前)=========================
		Map<String, Object> overdueMilepostResult = new HashMap<>();
		StringBufferProxy overdueMilepostSql = new StringBufferProxy();
		if (projectList != null && projectList.size() > 0) {
			overdueMilepostSql.appendSingle("isfinished = {0}", 0);// 未达成
			overdueMilepostSql.appendSingle(" and planfinishtime <{0}", "to_date('"
					+ cn.hutool.core.date.DateUtil.formatDateTime(new Date()) + "','yyyy-mm-dd hh24:mi:ss')");
			if (projectList.size()<1000){
				overdueMilepostSql.appendSingle(" and (0,projectid) in (");
				for (PmProjectEntity project : projectList) {
					overdueMilepostSql.appendSingle("(0,'{0}'),", project.getId());
				}
			}else {

			}
			overdueMilepostSql = overdueMilepostSql.substring(0, overdueMilepostSql.length() - 1);
			overdueMilepostSql.appendSingle(")");
			List<PmMilepostEntity> milepostList = pmMilepostService.queryByWhere(overdueMilepostSql.toString());
			overdueMilepostResult.put("code", "overdueMilepostNum");
			overdueMilepostResult.put("name", "超期里程碑");
			overdueMilepostResult.put("iconImg", "/static/images/paojectManager/overdueMilepost.png");
			overdueMilepostResult.put("value", milepostList.size());
			resultMapList.add(overdueMilepostResult);
		} else {
			overdueMilepostResult.put("code", "overdueMilepostNum");
			overdueMilepostResult.put("iconImg", "/static/images/paojectManager/overdueMilepost.png");
			overdueMilepostResult.put("name", "超期里程碑");
			overdueMilepostResult.put("value", 0);
			resultMapList.add(overdueMilepostResult);
		}
		// =========================统计风险(和项目绑定的所有风险)=========================
		Map<String, Object> riskMap = new HashMap<>();
		StringBufferProxy riskSql = new StringBufferProxy();
		if (projectList != null && projectList.size() > 0) {
			riskSql.appendSingle("(0,projectid) in (");
			for (PmProjectEntity project : projectList) {
				riskSql.appendSingle("(0,'{0}'),", project.getId());
			}
			riskSql = riskSql.substring(0, riskSql.length() - 1);
			riskSql.appendSingle(")");
			List<PmRiskIdentifyEntity> riskList = pmRiskIdentifyService.queryByWhere(riskSql.toString());
			riskMap.put("code", "riskNum");
			riskMap.put("name", "现存风险");
			riskMap.put("iconImg", "/static/images/paojectManager/risk.png");
			riskMap.put("value", riskList.size());
			resultMapList.add(riskMap);
		} else {
			riskMap.put("code", "riskNum");
			riskMap.put("name", "现存风险");
			riskMap.put("iconImg", "/static/images/paojectManager/risk.png");
			riskMap.put("value", 0);
			resultMapList.add(riskMap);
		}
		// =========================统计问题(未处理和处理中的问题)=========================
		Map<String, Object> problemMap = new HashMap<>();
		StringBufferProxy problemSql = new StringBufferProxy();
		if (projectList != null && projectList.size() > 0) {
			problemSql.appendSingle("problemstate in (1,2)");
			problemSql.appendSingle(" and (0,projectid) in (");
			for (PmProjectEntity project : projectList) {
				problemSql.appendSingle("(0,'{0}'),", project.getId());
			}
			problemSql = problemSql.substring(0, problemSql.length() - 1);
			problemSql.appendSingle(")");
			List<PmProblemsEntity> problemList = pmProblemsService.queryByWhere(problemSql.toString());
			problemMap.put("code", "problemNum");
			problemMap.put("iconImg", "/static/images/paojectManager/problems.png");
			problemMap.put("name", "现存问题");
			problemMap.put("value", problemList.size());
			resultMapList.add(problemMap);
		} else {
			problemMap.put("code", "problemNum");
			problemMap.put("name", "现存问题");
			problemMap.put("iconImg", "/static/images/paojectManager/problems.png");
			problemMap.put("value", 0);
			resultMapList.add(problemMap);
		}

		// =========================今日任务数量(非完成和取消的任务)=========================
		List<PmTaskEntity> taskList = new ArrayList<>();
		Map<String, Object> taskMap = new HashMap<>();
		StringBufferProxy taskSql = new StringBufferProxy();
		if (projectList != null && projectList.size() > 0) {
			taskSql.appendSingle("taskstate in (1,2,3)");
			taskSql.appendSingle(" and (0,projectid) in (");
			for (PmProjectEntity project : projectList) {
				taskSql.appendSingle("(0,'{0}'),", project.getId());
			}
			taskSql = taskSql.substring(0, taskSql.length() - 1);
			taskSql.appendSingle(")");
			DateTime beginOfDay = cn.hutool.core.date.DateUtil.beginOfDay(new Date());
			DateTime endOfDay = cn.hutool.core.date.DateUtil.endOfDay(new Date());
			String beginDateStr = cn.hutool.core.date.DateUtil.formatDateTime(beginOfDay);
			String endDateStr = cn.hutool.core.date.DateUtil.formatDateTime(endOfDay);
			// 只查询当日任务
			taskSql.appendSingle(
					" and createon between to_date('{0}','yyyy-mm-dd hh24:mi:ss') and  to_date('{1}','yyyy-mm-dd hh24:mi:ss')",
					beginDateStr, endDateStr);
			taskList = pmTaskService.queryByWhere(taskSql.toString());
			taskMap.put("code", "taskNum");
			taskMap.put("name", "当日任务数");
			taskMap.put("iconImg", "/static/images/paojectManager/task.png");
			taskMap.put("value", taskList.size());
			resultMapList.add(taskMap);
		} else {
			taskMap.put("code", "taskNum");
			taskMap.put("name", "当日任务数");
			taskMap.put("iconImg", "/static/images/paojectManager/task.png");
			taskMap.put("value", 0);
			resultMapList.add(taskMap);
		}
		// =========================今日人力投入(所有项目中的项目参与人和负责人总数量)=========================
		Map<String, Object> personMap = new HashMap<>();
		if (taskList != null && taskList.size() > 0) {
			int personNum = 0;
			for (PmTaskEntity task : taskList) {
				if (!StringUtil.isEmpty(task.getParticipantcodes()))
				{
					personNum = personNum + task.getParticipantcodes().split(",").length;
				}
			}
			personMap.put("code", "personNum");
			personMap.put("name", "当日人天数");
			personMap.put("iconImg", "/static/images/paojectManager/person.png");
			personMap.put("value", personNum+1);
			resultMapList.add(personMap);
		} else {
			personMap.put("code", "personNum");
			personMap.put("name", "当日人天数");
			personMap.put("iconImg", "/static/images/paojectManager/person.png");
			personMap.put("value", 0);
			resultMapList.add(personMap);

		}
		// =========================日志情况(填写数量/下发数量，项目经理审核数量)=========================
		Map<String, Object> taskLogCount = new HashMap<>();
		taskLogCount = pmTaskLogService.getFilledAndCreatAndApprovedCount(this.getUserBean().getUser());
		if (taskLogCount != null) {
			StringBufferProxy nameStr = new StringBufferProxy();
			nameStr.appendSingle("自上月26号以来，您已填报的工作量为:{0}/人天,项目经理已确认的工作量为{1}/人天。",ConvertUtil.convertToString(taskLogCount.get("filledTaskLogCount"))
			, ConvertUtil.convertToString(taskLogCount.get("approvaledTaskLogCount")));
			taskLogCount.put("code", "taskLogCount");
			taskLogCount.put("name", nameStr.toString());
			taskLogCount.put("iconImg", "/static/images/paojectManager/person.png");
			taskLogCount.put("value", "");
		}
		Map<String, Object> resultmap = new HashMap<>();
		resultmap.put("exceptionList",resultMapList);
		resultmap.put("taskLogInfo",taskLogCount);
		return ResponseResult.ok(resultmap);
	}

	/**
	 * @param paraMap
	 * @return
	 * @author: liwanpeng
	 * @date: 2020-05-18
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			Query query = new Query(paraMap);
			String sqlWhere = this.spellListSqlRef(paraMap);
			int totalCount = ((ITapService)this.service).getCount(sqlWhere);
			List<Map<String, Object>> tempList = null;
			if (query.getPageSize() > 0) {
				tempList = ((ITapService)this.service).queryMapForPage(sqlWhere, query.getCurrentPage(), query.getPageSize(), query.getSidx(), query.getSord());
			} else {
				tempList = ((ITapService)this.service).queryMapByWhere(sqlWhere);
			}

			Page page = new Page(tempList, totalCount, query.getPageSize(), query.getCurrentPage());
			return ResponseResult.ok(page);
		} catch (Exception var7) {
			return this.handleControllerException(var7);
		}
	}

	/**
	 * @param dataMap
	 * @param paraMap
	 * @throws Exception
	 * @description: 提交审批前
	 * @author: liwanpeng
	 * @date: 2020-05-18
	 * @modify:
	 */
	@Override
	protected void beforeSubmit(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
		super.beforeSubmit(dataMap, paraMap);
		StringBufferProxy mailtitle = new StringBufferProxy();
		mailtitle.appendSingle("{0}{1}于{2}提交项目基本信息申请,单据编号{3}! ", dataMap.get("dispdeptcode"), dataMap.get("username"),
				DateUtil.dateToString(new Date(), "yyyy-MM-dd"), dataMap.get("docno"));
		dataMap.put("maintitle", mailtitle.toString());
		List<Map<String, Object>> flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_PmProject", dataMap.get("deptcode").toString(),dataMap.get("usercode").toString(),null, "sortcode");
		Long flowid = flowidList.size()>0? ConvertUtil.convertToLong(flowidList.get(0).get("id")) :null;
		dataMap.put("flowid", flowid);
	}

	/**
	 * 数据大屏接数据中心、项目数据接口
	 *
	 * @return
	 */
	@GetMapping("/dataBigScreen")
	public ResponseResult<Object> bigScreenData(@RequestParam(required = false) Map<String, Object> paraMap) {
		Map<String, Object> result = new HashMap<>();
		// 大屏中（thisYear:今年 lastYear:去年 beforLastYear:前年 ）
		// 查询时间
		String queryTime = "";
		if ("thisYear".equals(ConvertUtil.convertToString(paraMap.get("timeFlag")))) {
			queryTime = cn.hutool.core.date.DateUtil
					.formatDateTime(cn.hutool.core.date.DateUtil.beginOfYear(new Date()));
		} else if ("lastYear".equals(ConvertUtil.convertToString(paraMap.get("timeFlag")))) {
			queryTime = cn.hutool.core.date.DateUtil.formatDateTime(cn.hutool.core.date.DateUtil
					.offsetMonth(cn.hutool.core.date.DateUtil.beginOfYear(new Date()), -12));

		} else if ("beforLastYear".equals(ConvertUtil.convertToString(paraMap.get("timeFlag")))) {
			queryTime = cn.hutool.core.date.DateUtil.formatDateTime(cn.hutool.core.date.DateUtil
					.offsetMonth(cn.hutool.core.date.DateUtil.beginOfYear(new Date()), -24));
		} else {
			return ResponseResult.error("时间标志（今年、去年、前年）标志为空。");
		}
		// 拼装查询sql
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("1=1");
		// 数据权限
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "","PmProjectForBigScreen",
					this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限查看所在公司的数据
			{
				sql.appendSingle(" and ownerorgcode='{0}'", this.getUserBean().getOrg().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		// 查询项目列表，按照立项时间进行时间段的筛选，默认是今年立项的所有项目
		sql.appendSingle(" and approvaltime >= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", queryTime);
		// 计算项目总金额
		List<PmProjectEntity> projectList = this.service.queryByWhere(sql.toString());
		BigDecimal projectMoneySum = new BigDecimal("0.0000");// 项目总金额
		BigDecimal contractMoneySum = new BigDecimal("0.0000");// 合同总金额
		BigDecimal invoiceMoneySum = new BigDecimal("0.0000");// 开票总金额
		BigDecimal recBillMoneySum = new BigDecimal("0.0000");// 收款总金额
		BigDecimal budgetMoneySum = new BigDecimal("0.0000");// 项目预算
		BigDecimal confirmrevenuemoneySum = new BigDecimal("0.0000");// 确认收入总金额
		BigDecimal purchasecontractmoneySum = new BigDecimal("0.0000");// 采购合同总金额
		BigDecimal costmoneySum = new BigDecimal("0.0000");// 成本总金额

		for (PmProjectEntity item : projectList) {
			projectMoneySum = projectMoneySum.add(item.getProjectmoney()==null?new BigDecimal(0):item.getProjectmoney());
			contractMoneySum = contractMoneySum.add(item.getContractmoney()==null?new BigDecimal(0):item.getContractmoney());
			invoiceMoneySum = invoiceMoneySum.add(item.getBillmoney()==null?new BigDecimal(0):item.getBillmoney());
			recBillMoneySum = recBillMoneySum.add(item.getRecbillmoney()==null?new BigDecimal(0):item.getRecbillmoney());
			budgetMoneySum = budgetMoneySum.add(item.getBudgetmoney()==null?new BigDecimal(0):item.getBudgetmoney());
			confirmrevenuemoneySum = confirmrevenuemoneySum.add(item.getConfirmrevenuemoney()==null?new BigDecimal(0):item.getConfirmrevenuemoney());
			purchasecontractmoneySum = purchasecontractmoneySum.add(item.getPurchasepaymentmoney()==null?new BigDecimal(0):item.getPurchasepaymentmoney());
			costmoneySum = costmoneySum.add(item.getCostmoney()==null?new BigDecimal(0):item.getCostmoney());
		}
		// 合同签约率（有合同金额/项目金额）
		result.put("contractRate",
				(contractMoneySum.divide(projectMoneySum, 4).setScale(4)).multiply(new BigDecimal(100)).setScale(2)
						+ "%");
		// 开票率（开票总金额/项目）
		result.put("invoiceRate",
				(invoiceMoneySum.divide(projectMoneySum, 4).setScale(4)).multiply(new BigDecimal(100)).setScale(2)
						+ "%");
		// 收款率（收款总金额/项目）
		result.put("recBillRate",
				(recBillMoneySum.divide(projectMoneySum, 4).setScale(4)).multiply(new BigDecimal(100)).setScale(2)
						+ "%");
		// 毛利率 ((项目金额-预算)/项目金额)
		result.put("profitRate", ((projectMoneySum.subtract(budgetMoneySum)).divide(projectMoneySum, 4).setScale(4))
				.multiply(new BigDecimal(100)).setScale(2) + "%");
		// 新项目数（今年/去年/前年以来签约的项目，即list.size）
		result.put("projectNum", projectList.size());
		// 报废项目数（今年/去年/前年以来签约的项目中处于报废状态的项目数量）
		// 筛选处于报废状态的项目
		List<PmProjectEntity> cancelProjectList = projectList.stream()
				.filter(item -> "21".equals(item.getProjectstate())).collect(Collectors.toList());
		result.put("cancelProjectNum", cancelProjectList.size());
		// 财务确认收入金额
		result.put("confirmrevenuemoneySum", confirmrevenuemoneySum);
		// 采购合同金额
		result.put("purchasepaymentmoneySum", purchasecontractmoneySum);
		// 项目金额
		result.put("projectMoneySum", projectMoneySum);
		// 合同总金额
		result.put("contractMoneySum", contractMoneySum);
		// 开票金额
		result.put("invoiceMoneySum", invoiceMoneySum);
		// 收款金额
		result.put("recBillMoneySum", recBillMoneySum);
		// 财务成本金额
		result.put("costmoneySum", costmoneySum);
		// 预算金额
		result.put("budgetMoneySum", budgetMoneySum);
		// 地图数据
		List<Map<String, Object>> mapDataList = new ArrayList<>();
		// 按照项目所属省份进行分组(地图数据)
		Map<String, List<PmProjectEntity>> projectWithProvince = projectList.stream()
				.collect(Collectors.groupingBy((PmProjectEntity::getProvince)));
		Set<Entry<String, List<PmProjectEntity>>> entrySet = projectWithProvince.entrySet();
		int maxNum = 0;
		for (Entry<String, List<PmProjectEntity>> item : entrySet) {
			if (item.getValue().size() > maxNum) {
				maxNum = item.getValue().size();
			}
			Map<String, Object> temp = new HashMap<>();
			String proviceName = datacodeCache.getValueDynamic("province",
					ConvertUtil.convertToString(item.getKey()).replace(" ",""), "code", "name");
			proviceName = getEchartsProvicename(proviceName);
			temp.put("name", proviceName);
			temp.put("value", item.getValue().size());
			mapDataList.add(temp);
		}
		result.put("mapData", mapDataList);
		// 地图最大数量
		result.put("mapMaxNum", maxNum);
		// 按照状态进行分组（饼图数据）
		List<Map<String, Object>> pieDataList = new ArrayList<>();
		Map<Long, List<PmProjectEntity>> projectWithProjctState = projectList.stream()
				.collect(Collectors.groupingBy(PmProjectEntity::getProjectstate));
		List<Map<String, Object>> codeListMap = datacodeCache.getCodeListMap("PmProjectState",
				" code not in('0','21','22')", "sortcode");
		for (Map<String, Object> item : codeListMap) {
			Map<String, Object> temp = new HashMap<>();
			// 是否有此状态标志
			boolean isHaveThisState = false;
			String dispProjectState = datacodeCache.getValueDynamic("PmProjectState",
					ConvertUtil.convertToString(item.get("code")), "code", "name");

			for (Entry<Long, List<PmProjectEntity>> itemEntry : projectWithProjctState.entrySet()) {
				if (ConvertUtil.convertToString(item.get("code"))
						.equals(ConvertUtil.convertToString(itemEntry.getKey()))) {
					temp.put("name", dispProjectState);
					temp.put("value", itemEntry.getValue().size());
					temp.put("code", itemEntry.getKey());
					isHaveThisState = true;
					break;
				}
			}
			// 没有此状态，赋默认值
			if (!isHaveThisState) {
				temp.put("name", dispProjectState);
				temp.put("value", 0);
				temp.put("code", ConvertUtil.convertToString(item.get("code")));
			}
			pieDataList.add(temp);
			isHaveThisState = false;
		}

		result.put("pieData", pieDataList);
		// 销售经理排名数据
		// 按照销售经理进行分组
		List<Map<String, Object>> saleManagerDataTop10 = new ArrayList<>();

		Map<String, List<PmProjectEntity>> projectWithSaleManager = projectList.stream()
				.collect(Collectors.groupingBy(PmProjectEntity::getAreamanagercode));
		for (Entry<String, List<PmProjectEntity>> item : projectWithSaleManager.entrySet()) {
			Map<String, Object> tempMap = new HashMap<>();
			BigDecimal tempSaleMoney = new BigDecimal(0);
			tempSaleMoney.setScale(2);
			// 计算分组中的总额
			for (PmProjectEntity project : item.getValue()) {
				tempSaleMoney = tempSaleMoney.add(project.getProjectmoney());
			}
			tempMap.put("areamanagerCode", item.getValue().get(0).getAreamanagercode());
			tempMap.put("areamanagerName", item.getValue().get(0).getAreamanagername());
			tempMap.put("money", tempSaleMoney.doubleValue());
			saleManagerDataTop10.add(tempMap);
		}
		// 排序
		List<Map<String, Object>> saleManagerDataTop10Sorted = saleManagerDataTop10.stream()
				.sorted(Comparator.comparing(this::sortedForMoney).reversed()).collect(Collectors.toList());
		// 截取前10名
		saleManagerDataTop10Sorted = saleManagerDataTop10Sorted.subList(0,
				saleManagerDataTop10Sorted.size() >= 10 ? 9 : saleManagerDataTop10Sorted.size());
		result.put("areamanagerTop10", saleManagerDataTop10Sorted);
		return ResponseResult.ok(result);
	}

	/**
	 * map排序方法获取属性（销售经理top10专用）
	 *
	 * @param paramMap
	 * @return
	 */
	private double sortedForMoney(Map<String, Object> paramMap) {
		return ConvertUtil.convertToDouble(paramMap.get("money"));
	}

	/**
	 * map排序方法获取属性（项目类型统计饼图专用）
	 *
	 * @param paramMap
	 * @return
	 */
	private double sortedForProjectType(Map<String, Object> paramMap) {
		return ConvertUtil.convertToDouble(paramMap.get("value"));
	}

	/**
	 * 待确认工时
	 *
	 * @return
	 */
	@GetMapping("/manHoursConfirm")
	public ResponseResult<Object> manHoursConfirmAndReccentlyProject(
			@RequestParam(required = false) Map<String, Object> paraMap) {

		StringBufferProxy sqlForTaskLog = new StringBufferProxy();
		sqlForTaskLog.appendSingle("1=1 ");
		// 公司数据
		if (this.getUserBean().getUser().getAdminlevel() < 1) {
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "","PmProjectForBigScreen",
					this.getUserBean());

			if (StringUtil.isEmpty(dataPession)) {
				if ("org".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
					sqlForTaskLog.appendSingle(MisStringUtil.createWhereByUsercodeFromProject(this.getUserBean().getUser(), "projectid", "pmtasklog"));
				} else if ("inChargeMe".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
					// 我负责的（项目经理是我）
					sqlForTaskLog.appendSingle(
							"and exists (select id from pmproject where pmproject.id = pmtasklog.projectid and pmproject.projectmanagercode = '{0}')",
							this.getUserBean().getUser().getCode());
				} else if ("participate".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
					// 我参与的（项目组成员中有我）
					sqlForTaskLog.appendSingle(
							"and exists(select projectid from pmteam where pmtasklog.projectid=pmteam.projectid and pmteam.usercode = '{0}')",
							this.getUserBean().getUser().getCode());
				} else {
					return null;
				}
			} else {
				sqlForTaskLog.appendSingle(" and {0} ", dataPession);
			}

		}
		//
		if (paraMap.containsKey("queryDate")) {
			String value = paraMap.get("queryDate").toString();
			if (!StringUtil.isEmpty(value)) {
				DateTime beginOfDay = cn.hutool.core.date.DateUtil.beginOfDay(
						cn.hutool.core.date.DateUtil.parseDate(ConvertUtil.convertToString(paraMap.get("queryDate"))));
				DateTime endOfDay = cn.hutool.core.date.DateUtil.endOfDay(
						cn.hutool.core.date.DateUtil.parseDate(ConvertUtil.convertToString(paraMap.get("queryDate"))));
				String beginDateStr = cn.hutool.core.date.DateUtil.formatDateTime(beginOfDay);
				String endDateStr = cn.hutool.core.date.DateUtil.formatDateTime(endOfDay);
				sqlForTaskLog.appendSingle(
						" and createon between to_date('{0}','yyyy-mm-dd hh24:mi:ss') and  to_date('{1}','yyyy-mm-dd hh24:mi:ss')",
						beginDateStr, endDateStr);
			}
		}
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		int totalCount = pmTaskLogService.getCount(sqlForTaskLog.toString());
		List<Map<String, Object>> queryMapForPage = pmTaskLogService.queryMapForPage(sqlForTaskLog.toString(),
				ConvertUtil.convertToInt(paraMap.get("currentPage")), ConvertUtil.convertToInt(paraMap.get("pageSize")),
				ConvertUtil.convertToString(paraMap.get("sidx")), ConvertUtil.convertToString(paraMap.get("sord")));
		Page page = new Page(queryMapForPage, totalCount, query.getPageSize(), query.getCurrentPage());
		return ResponseResult.ok(page);
	}

	/**
	 * 查询即将超期的任务
	 *
	 * @param paraMap
	 * @return
	 */

	@GetMapping(value = "/queryTaskSoonOverdue")
	public ResponseResult<Object> queryTaskSoonOverdue(@RequestParam(required = false) Map<String, Object> paraMap) {
		StringBufferProxy sqlForReccentlyProject = new StringBufferProxy();
		sqlForReccentlyProject.appendSingle("select id from PmProject where pmtask.PROJECTID = PmProject.id and ");
		// 公司数据
		if ("org".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
			sqlForReccentlyProject.appendSingle(" ownerorgcode = '{0}'", this.getUserBean().getOrg().getCode());
		} else if ("inChargeMe".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
			// 我负责的（项目经理是我）
			sqlForReccentlyProject.appendSingle("projectmanagercode = '{0}'", this.getUserBean().getUser().getCode());
		} else if ("participate".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
			// 我参与的（项目组成员中有我）
			sqlForReccentlyProject.appendSingle(
					" exists(select projectid from pmteam where pmproject.id=pmteam.projectid and pmteam.usercode = '{0}')",
					this.getUserBean().getUser().getCode());
		} else {
			return null;
		}
		StringBufferProxy sqlForTask = new StringBufferProxy();
		sqlForTask.appendSingle("exists ({0})", sqlForReccentlyProject);
		// 查询一周内或者3天内超期的项目
		if ("oneWeek".equals(ConvertUtil.convertToString(paraMap.get("timeFlag")))) {
			// 查询计划完成时间在当前时间的后一周内的项目
			DateTime beginTime = cn.hutool.core.date.DateUtil.offsetDay(new Date(), 7);

			sqlForTask.appendSingle(
					" and endtime between to_date('{0}','yyyy-mm-dd hh24:mi:ss') and  to_date('{1}','yyyy-mm-dd hh24:mi:ss')",
					cn.hutool.core.date.DateUtil.formatDateTime(new Date()),
					cn.hutool.core.date.DateUtil.formatDateTime(beginTime));
		} else if ("threeDays".equals(ConvertUtil.convertToString(paraMap.get("timeFlag")))) {
			// 查询计划完成时间在当前时间后3天内的项目
			DateTime beginTime = cn.hutool.core.date.DateUtil.offsetDay(new Date(), 3);

			sqlForTask.appendSingle(
					" and endtime between to_date('{0}','yyyy-mm-dd hh24:mi:ss') and  to_date('{1}','yyyy-mm-dd hh24:mi:ss')",
					cn.hutool.core.date.DateUtil.formatDateTime(new Date()),
					cn.hutool.core.date.DateUtil.formatDateTime(beginTime));
		}
		Query query = new Query(paraMap);
		int totalCount = pmTaskService.getCount(sqlForTask.toString());
		List<Map<String, Object>> queryMapForPage = pmTaskService.queryMapForPage(sqlForTask.toString(),
				ConvertUtil.convertToInt(paraMap.get("currentPage")), ConvertUtil.convertToInt(paraMap.get("pageSize")),
				ConvertUtil.convertToString(paraMap.get("sidx")), ConvertUtil.convertToString(paraMap.get("sord")));
		List<PmTaskEntity> taskLog = pmTaskService.queryByWhere(sqlForTask.toString());
		Page page = new Page(queryMapForPage, totalCount, query.getPageSize(), query.getCurrentPage());

		// PmProjectEntity pmProjectEntity = this.service.queryById(projectId);
		return ResponseResult.ok(page);
	}

	/**
	 * 最近创建项目接口
	 *
	 * @return
	 */
	@GetMapping("/reccentlyProject")
	public ResponseResult<Object> reccentlyProject(@RequestParam(required = false) Map<String, Object> paraMap) {
		StringBufferProxy sqlForReccentlyProject = new StringBufferProxy();
		// 公司数据
		if ("org".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
			sqlForReccentlyProject.appendSingle("ownerorgcode = '{0}'", this.getUserBean().getOrg().getCode());
		} else if ("inChargeMe".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
			// 我负责的（项目经理是我）
			sqlForReccentlyProject.appendSingle("projectmanagercode = '{0}'", this.getUserBean().getUser().getCode());
		} else if ("participate".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
			// 我参与的（项目组成员中有我）
			sqlForReccentlyProject.appendSingle(
					" exists(select projectid from pmteam where pmproject.id=pmteam.projectid and pmteam.usercode = '{0}')",
					this.getUserBean().getUser().getCode());
		} else {
			return null;
		}
		String beginDateStr = cn.hutool.core.date.DateUtil
				.formatDateTime(cn.hutool.core.date.DateUtil.beginOfMonth(new Date()));
		String endDateStr = cn.hutool.core.date.DateUtil
				.formatDateTime(cn.hutool.core.date.DateUtil.endOfMonth(new Date()));
		sqlForReccentlyProject.appendSingle(
				" and {2} between to_date('{0}','yyyy-mm-dd hh24:mi:ss') and  to_date('{1}','yyyy-mm-dd hh24:mi:ss')",
				beginDateStr, endDateStr, ConvertUtil.convertToString(paraMap.get("timeColName")));
		paraMap = BaseUtil.decodeSecureMap(paraMap);
		Query query = new Query(paraMap);
		int totalCount = this.service.getCount(sqlForReccentlyProject.toString());
		List<Map<String, Object>> queryMapForPage = this.service.queryMapForPage(sqlForReccentlyProject.toString(),
				ConvertUtil.convertToInt(paraMap.get("currentPage")), ConvertUtil.convertToInt(paraMap.get("pageSize")),
				ConvertUtil.convertToString(paraMap.get("sidx")), ConvertUtil.convertToString(paraMap.get("sord")));
		Page page = new Page(queryMapForPage, totalCount, query.getPageSize(), query.getCurrentPage());
		return ResponseResult.ok(page);
	}

	/**
	 * 首页项目列表权限
	 * @return
	 */
	public List<PmProjectEntity> sysIndexProject(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("1=1 ");
		if (this.getUserBean().getUser().getAdminlevel() < 1) {
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "","PmProject", this.getUserBean());

			if (StringUtil.isEmpty(dataPession)) {
				// 公司数据
				if ("org".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
					sql.appendSingle(" and ownerorgcode = '{0}'", this.getUserBean().getOrg().getCode());
				} else if ("inChargeMe".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
					// 我负责的（项目经理是我）
					sql.appendSingle(" and projectmanagercode = '{0}'", this.getUserBean().getUser().getCode());
				} else if ("participate".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
					// 我参与的（项目组成员中有我）
					sql.appendSingle(
							" and exists(select projectid from pmteam where pmproject.id=pmteam.projectid and pmteam.usercode = '{0}')",
							this.getUserBean().getUser().getCode());
				} else {
					return null;
				}
			} else {
				sql.appendSingle(" and {0} ", dataPession);
			}
		}

		// 查询有权限的项目
		List<PmProjectEntity> projectList = this.service.queryByWhere(sql.toString());
		return projectList;
	}
	/**
	 * 首页项目列表权限
	 * @return
	 */
	public List<PmProjectEntity> sysIndexProjectpprovaltimeIsNotNull(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle("1=1  ");
		if (this.getUserBean().getUser().getAdminlevel() < 1) {
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, "","PmProject", this.getUserBean());

			if (StringUtil.isEmpty(dataPession)) {
				// 公司数据
				if ("org".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
					sql.appendSingle(" and ownerorgcode = '{0}'", this.getUserBean().getOrg().getCode());
				} else if ("inChargeMe".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
					// 我负责的（项目经理是我）
					sql.appendSingle(" and projectmanagercode = '{0}'", this.getUserBean().getUser().getCode());
				} else if ("participate".equals(ConvertUtil.convertToString(paraMap.get("dataPermissionFlag")))) {
					// 我参与的（项目组成员中有我）
					sql.appendSingle(
							" and exists(select projectid from pmteam where pmproject.id=pmteam.projectid and pmteam.usercode = '{0}')",
							this.getUserBean().getUser().getCode());
				} else {
					return null;
				}
			} else {
				sql.appendSingle(" and {0} ", dataPession);
			}
		}

		// 查询有权限的项目
		List<PmProjectEntity> projectList = this.service.queryByWhere(sql.toString());
		return projectList;
	}
	/**
	 * 数据权限（通用）
	 *
	 * @param paramMap
	 * @return
	 */
	public String permissionString(Map<String, Object> paramMap, String datapermissionModule) {
		StringBufferProxy sql = new StringBufferProxy();
		if (this.getUserBean().getUser().getAdminlevel() < 1)// 管理员、超级管理员，不控制权限
		{
			String dataPession = service.getDataPermission(TapOperationTypeEnum.Select, datapermissionModule,
					this.getUserBean());
			if (StringUtil.isEmpty(dataPession))// 默认权限只能看我是项目经理、销售经理、项目组成员的项目
			{
				sql.appendSingle(" and (areamanagercode = '{0}' or projectmanagercode = '{0}'",
						this.getUserBean().getUser().getCode());
				sql.appendSingle(
						" or exists(select projectid from pmteam where pmproject.id=pmteam.projectid and pmteam.usercode = '{0}'))",
						this.getUserBean().getUser().getCode());
			} else// 使用数据权限
			{
				sql.appendSingle(" and {0} ", dataPession);
			}
		}
		return sql.toString();
	}

	/**
	 * @throws Exception
	 * @description: 保存前
	 * @author: liwanpeng
	 * @date: 2020-05-18
	 * @modify:
	 */
	// @Override
	// protected void beforeInsert(Map<String, Object> dataMap, Map<String, Object>
	// paraMap) throws Exception {
	// SessionUserBean userBean = this.getUserBean();
	// paraMap.put("orgname", userBean.getOrg().getName());
	// paraMap.put("deptname", userBean.getDept().getName());
	// paraMap.put("usercode", userBean.getUser().getCode());
	// paraMap.put("code", userBean.getUser().getCode());
	// if (paraMap.get("projectstate") == null ||
	// "".equals(paraMap.get("projectstate"))) {
	// paraMap.put("projectstate", 0);
	// }
	// paraMap.put("username", userBean.getUser().getName());
	// // paraMap.put("orgname", userBean.getOrg().getName());
	// }

	public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
		Map<Object, Boolean> seen = new ConcurrentHashMap<>();
		return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
	}

	@GetMapping("getProjectRole")
	public ResponseResult<Object> getProjectRole(@RequestParam(required = false) Map<String, Object> paramMap) {
		// 先从项目成员中获取
		StringBufferProxy teamSql = new StringBufferProxy();
		teamSql.appendSingle("enabled = 1 and projectid = {0} and usercode ={1}",
				ConvertUtil.convertToString(paramMap.get("projectId")), this.getUserBean().getUser().getCode());
		List<PmTeamEntity> teamList = pmTeamService.queryByWhere(teamSql.toString());
		// 同一个项目团队中同一个人只能出现一次，此处默认第一个就是当前人的项目成员信息
		if (teamList != null && teamList.size() >= 1) {
			return ResponseResult.ok(Integer.valueOf(teamList.get(0).getRole()));
		} else {
			// 如果项目团队中没有当前用户，则查询项目基本信息
			PmProjectEntity projectInfo = this.service
					.queryById(ConvertUtil.convertToString(paramMap.get("projectId")));
			// 如果是项目经理则返回项目经理角色
			if (projectInfo.getProjectmanagercode().equals(this.getUserBean().getUser().getCode())) {
				return ResponseResult.ok(2);
			} else {
				return ResponseResult.error("抱歉您没有任何项目角色。");
			}
		}

	}

	/**
	 * 获取echarts中的省份名称
	 *
	 * @return
	 */
	public String getEchartsProvicename(String provinceFull) {
		String provinceEcharts = "";
		if (provinceFull.contains("省") || provinceFull.contains("市")) {
			provinceEcharts = provinceFull.substring(0, provinceFull.length() - 1);
		} else if (provinceFull.contains("族自治区")) {
			provinceEcharts = provinceFull.substring(0, 2);
		} else if (provinceFull.contains("自治区")) {
			provinceEcharts = provinceFull.substring(0, provinceFull.length() - 3);
		} else if (provinceFull.contains("特别行政区")) {
			provinceEcharts = provinceFull.substring(0, 2);
		} else {
			provinceEcharts = provinceFull;
		}
		return provinceEcharts;
	}

	@GetMapping("/getProjectSysParam")
	public ResponseResult<Object> getProjectSysParam(@RequestParam(required = false) Map<String, Object> paramMap) {
		CboSysParamService cboSysParamService = (CboSysParamService)SpringUtil.getBean("cboSysParamService");
		List<CboSysParamEntity> paramEntities = cboSysParamService.queryByWhere(" code like 'Project%'");
		// 只对沈阳科远做毛利率的控制
		if(paramMap.containsKey("projectOrg")&&ConvertUtil.convertToString(paramMap.get("projectOrg")).equals("D26")){
			return ResponseResult.ok(paramEntities);
		}else {
			for (CboSysParamEntity item:paramEntities){
				if (item.getCode().equals("ProjectMinProfit")||item.getCode().equals("ProjectTipsMinProfit")){
					item.setParamvalue("-1000000");
				}
			}
			return ResponseResult.ok(paramEntities);

		}

	}

	// @Autowired
	// private PmCboMessageAppService pmCboMessageAppService;
	// @GetMapping("test")
	// public void testPushAppMessage() {
	//// ICboMessageAppService cboMessageAppService =
	// (ICboMessageAppService)SpringUtil.getBean("pmCboMessageAppService");
	// //推送消息
	//// ischange = true;
	// Map<String, Object> messageAppmap = new HashMap<String, Object>();
	// messageAppmap.put("usercode","9012");
	// messageAppmap.put("content", "工程项目系统推送测试");
	// messageAppmap.put("extendfield1", "工程项目系统推送测试");
	// messageAppmap.put("sendtype", "0");
	// int insertMap = pmCboMessageAppService.insertMap(messageAppmap);
	// System.out.println(insertMap);
	// }
	public static void main(String[] args) {
		DateTime beginOfDay = cn.hutool.core.date.DateUtil.beginOfDay(new Date());

		System.out.println(cn.hutool.core.date.DateUtil.formatDateTime(beginOfDay));
		// System.out.println(getEchartsProvicename(""));
	}
}
